// router/router.go
// Sets up Gin routes and middleware for the AgentDesign API server.

package router

import (
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"

	"agentdesign/handlers"
)

// SetupRouter creates a Gin engine, applies middleware and registers API routes.
func SetupRouter(handler *handlers.Handler) *gin.Engine {
	r := gin.Default()

	// Enable Cross-Origin Resource Sharing with the default permissive settings.
	r.Use(cors.Default())

	api := r.Group("/api")
	{
		// Prompt generation endpoint.
		api.POST("/prompt", handler.HandlePrompt)
		api.GET("/prompt/requests", handler.ListPromptRequests)

		// Project routes.
		projects := api.Group("/projects")
		{
			projects.GET("", handler.ListProjects)
			projects.POST("", handler.CreateProject)
			projects.GET("/:id", handler.GetProject)
			projects.PUT("/:id", handler.UpdateProject)
			projects.DELETE("/:id", handler.DeleteProject)

			pages := projects.Group("/:id/pages")
			{
				pages.GET("", handler.ListProjectPages)
				pages.POST("", handler.CreateProjectPage)
				pages.GET("/:pageId", handler.GetProjectPage)
				pages.PUT("/:pageId", handler.UpdateProjectPage)
				pages.DELETE("/:pageId", handler.DeleteProjectPage)

				canvas := pages.Group("/:pageId/canvas")
				{
					canvas.GET("/messages", handler.ListCanvasMessages)
					canvas.POST("/messages", handler.CreateCanvasMessage)
					canvas.GET("/sections/latest", handler.ListLatestSection)
					canvas.GET("/sections", handler.ListPageSections)
					canvas.POST("/sections", handler.CreatePageSection)
					canvas.PUT("/sections/:sectionId", handler.UpdatePageSection)
					canvas.DELETE("/sections/:sectionId", handler.DeletePageSection)
				}

				prompt := pages.Group("/:pageId/prompt")
				{
					prompt.POST("", handler.HandlePrompt)
				}
			}
		}

		// Template catalog and recent history feeds.
		api.GET("/templates", handler.ListTemplates)
		api.GET("/history/recent", handler.ListRecentHistory)

		// Configuration presets for settings.
		api.GET("/configuration/presets", handler.ListConfigurationPresets)
	}

	return r
}
